package imchat

import (
	"net/http"
	"net/url"
	"strconv"

	"mall/common/utils/pointy"
	"mall/service/user/api/internal/logic/imchat"
	"mall/service/user/api/internal/svc"
	"mall/service/user/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
)

// 即时聊天
func ImChatHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.ChatReq
		u, err := url.Parse(r.RequestURI)
		if err != nil {
			logx.Infof("Error Parse URL Error:%+v", err)
			return
		}

		params, err := url.ParseQuery(u.RawQuery)
		if err != nil {
			logx.Infof("Error ParseQuery query Error:%+v", err)
			return
		}

		userId, err := strconv.ParseUint(params.Get("userId"), 10, 64)
		if err != nil {
			logx.Infof("Error userId ParseUint Error:%+v", err)
			return
		}

		req.UserID = pointy.GetPointer(userId)
		l := imchat.NewImChatLogic(r.Context(), svcCtx)
		resp, err := l.ImChat(&req, w, r)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}
